import { createRouter, createWebHistory } from "vue-router"
import pinia from '../store'
import { useRouterStore, useIndexStore } from "../store/path"
const routerStore = useRouterStore(pinia)
const indexStore = useIndexStore(pinia)
const index = () => import("@/views/home/index.vue")
const home = () => import("@/views/home/index/index.vue")
const attachment = () => import("@/views/home/attachment/index.vue")
const addPatient = () => import("@/views/home/addPatient/index.vue")
const viewProfile = () => import("@/views/home/viewProfile/index.vue")
const bloodPreasure = () => import("@/views/home/bloodPreasure/index.vue")
const setting = () => import("@/views/home/setting/index.vue")
const notFound = () => import("@/views/notFound/index.vue")
const userLogin = () => import("@/views/user/login.vue")

const routes = [
    {
        path: "/",
        name: 'index',
        component: index,
        redirect: '/home',
        children: [
            {
                path: 'home',
                name: 'home',
                component: home,
            },
            {
                path: 'attachment',
                name: 'attachment',
                component: attachment
            },
            {
                path: 'setting',
                name: 'setting',
                component: setting
            },
            {
                path: 'addPatient',
                name: 'addPatient',
                component: addPatient
            },
            {
                path: 'viewProfile',
                name: 'viewProfile',
                component: viewProfile
            },
            {
                path: 'bloodPreasure',
                name: 'bloodPreasure',
                component: bloodPreasure
            },
        ]
    },
    {
        path: '/404',
        name: '404',
        component: notFound
    },
    {
        path: '/user/login',
        name: 'login',
        component: userLogin
    },
    {
        path: '/:pathMatch(.*)',
        redirect: '/404'
    }
]


const router = createRouter({
    history: createWebHistory(),
    linkActiveClass: 'active',
    routes: routes,
    scrollBehavior() {
        return { top: 0 }
    },
})
router.beforeEach((to, from, next) => {
    routerStore.$patch({
        currentPage: to.name
    })
    // 获取当前token状态
    const tokenInStore = indexStore.token
    const tokenInStorage = sessionStorage.getItem('token')

    // 同步token逻辑
    if (tokenInStore) {
        // 当store有token时同步到sessionStorage
        sessionStorage.setItem('token', tokenInStore)
    } else if (tokenInStorage) {
        // 当sessionStorage有token时同步到store
        indexStore.$patch({ token: tokenInStorage })
    }

    // 同步后检查登录状态
    const hasToken = indexStore.token || sessionStorage.getItem('token')

    if (!hasToken) {
        // 无token且目标不是登录页时重定向
        if (to.path !== '/user/login') {
            return next('/user/login')
        }
    }

    next()
})

// 优化后的路由守卫（网页7、网页8）
// router.beforeEach(async (to) => {
//     // 新增：排除404和登录页的认证检查
//     if (to.name === '404' || to.name === 'login') return

//     // 同步token状态（新增清除无效token逻辑）
//     const token = indexStore.token || sessionStorage.getItem('token')
//     if (token && !indexStore.token) {
//         indexStore.$patch({ token })
//     } else if (!token) {
//         sessionStorage.removeItem('token')
//     }

//     // 优化登录页重定向逻辑
//     if (to.name === 'login' && token) {
//         return { name: 'home', replace: true }
//     }

//     // 需要认证的页面检查（新增token有效性验证）
//     if (to.matched.some(record => record.meta.requiresAuth)) {
//         if (!token || !isValidToken(token)) { // 需实现token有效性验证函数
//             return {
//                 path: '/user/login',
//                 query: { redirect: to.fullPath },
//                 replace: true
//             }
//         }
//     }
// })

// // 全局错误处理（网页2）
// router.onError((error) => {
//     console.error('[Router Error]', error)
//     if (error.name === 'NavigationDuplicated') return
//     router.replace('/404')
// })

// // 处理重复导航错误（网页4）
// const originalPush = router.push
// router.push = function push(location) {
//     return originalPush.call(this, location).catch(err => {
//         if (err.name !== 'NavigationDuplicated') throw err
//     })
// }

export default router